package com.ruoyi.sl.controller;

import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.sl.domain.*;
import com.ruoyi.sl.pojo.SlHrworkQuery;
import com.ruoyi.sl.pojo.SlProductionQuery;
import com.ruoyi.sl.pojo.SlRworkDateForm;
import com.ruoyi.sl.service.*;
import com.ruoyi.system.service.ISysDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 报工单Controller
 * 
 * @author admin
 * @date 2024-06-06
 */
@RestController
@RequestMapping("/sl/rwork")
public class SlRworkController extends BaseController
{
    @Autowired
    private ISlRworkService slRworkService;

    @Autowired
    private ISlRworkRmemberService slRworkRmemberService;

    @Autowired
    private ISlTeamService slTeamService;

    @Autowired
    private ISlGprocessService slGprocessService;
    @Autowired
    private ISlModuleService slModuleService;
    @Autowired
    private ISlWorkshopService slWorkshopService;
    @Autowired
    private ISlColourService slColourService;

    @Autowired
    private ISlBreedService slBreedService;

    @Autowired
    private ISlProcessService slProcessService;

    @Autowired
    private ISlAttendanceService slAttendanceService;
    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 产量查询
     */
    @PostMapping("/production")
    public AjaxResult getProList(@RequestBody SlProductionQuery slProductionQuery)
    {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(slProductionQuery.getDate());

        List list = slRworkService.selectProductionByQuery(calendar.get(Calendar.YEAR),slProductionQuery.getStrType(),slProductionQuery.getModuleId(),slProductionQuery.getWorkshopId());
        return success(list);
    }

    /**
     * 获取最后一次报工项操作人
     */
    @PreAuthorize("@ss.hasPermi('sl:rwork:query')")
    @GetMapping(value = "/lastmember")
    public AjaxResult getLastInfo()
    {
        AjaxResult ajax = AjaxResult.success();
        SlRwork slRwork = slRworkService.selectSlRworkByLast(getLoginUser().getUsername(),DateUtils.dateTime(DateUtils.YYYY_MM_DD,DateUtils.getDate()));
        if(StringUtils.isNotNull(slRwork)){
            List<SlRworkRmember> list = slRworkRmemberService.selectSlRworkRmemberListByRworkId(slRwork.getRworkId());
            for (SlRworkRmember slRworkRmember:list) {
                slRworkRmember.setRmemberId(null);
                slRworkRmember.setRworkId(null);
                slRworkRmember.setRfworkId(null);
            }
            ajax.put(AjaxResult.DATA_TAG, list);
        }
        return ajax;
    }


    /**
     * 查询未提交的报工项列表
     */
    @GetMapping("/notlist")
    public TableDataInfo notlist(SlRwork slRwork)
    {
        //只查询登录用户自己
        LoginUser loginUser = getLoginUser();
        slRwork.setRworkUser(getLoginUser().getUsername());
        List<SlRwork> list = slRworkService.selectSlRworkListByNoSubmit(slRwork);
        return getDataTable(list);

    }


    /**
     * 根据报工单ID查询报工项
     */
    @GetMapping(value =  "/rfw/{rfworkId}")
    public TableDataInfo getListByrfworkId(@PathVariable("rfworkId") Long rfworkId)
    {
        List<SlRwork> list = slRworkService.selectSlRworkListByRfworkId(rfworkId);
        return getDataTable(list);
    }

    /**
     * 查询报工项列表
     */
    @PreAuthorize("@ss.hasPermi('sl:rwork:list')")
    @GetMapping("/list")
    public TableDataInfo list(SlRwork slRwork)
    {
        startPage();
        //只查询登录用户自己的当日的报工
        LoginUser loginUser = getLoginUser();

        slRwork.setRworkUser(getLoginUser().getUsername());
        slRwork.setRworkDate(DateUtils.dateTime(DateUtils.YYYY_MM_DD,DateUtils.getDate()));

        List<SlRwork> list = slRworkService.selectSlRworkList(slRwork);
        return getDataTable(list);
    }


    /**
     * 历史报工项查询
     */
    @PreAuthorize("@ss.hasPermi('sl:rwork:list')")
    @GetMapping("/hlist")
    public TableDataInfo hlist(SlHrworkQuery slHrworkQuery)
    {
        List<SlRwork> list;
        if(StringUtils.isNotNull(slHrworkQuery.getMemberUser())){
            list = slRworkService.selectSlRworkListByRfworkIdAndMember(slHrworkQuery.getRfworkId(),slHrworkQuery.getMemberUser());
        }else{
            list = slRworkService.selectSlRworkListByRfworkId(slHrworkQuery.getRfworkId());
        }
        return getDataTable(list);
    }

    /**
     * 导出报工项列表
     */
    @PreAuthorize("@ss.hasPermi('sl:rwork:export')")
    @Log(title = "报工单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SlRwork slRwork)
    {
        //如果不是管理员则只查询登录用户自己的报工
        LoginUser loginUser = getLoginUser();
        if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin()){
            slRwork.setRworkUser(getLoginUser().getUsername());
            slRwork.setRworkDate(DateUtils.dateTime(DateUtils.YYYY_MM_DD,DateUtils.getDate()));
        }
        List<SlRwork> list = slRworkService.selectSlRworkList(slRwork);
        ExcelUtil<SlRwork> util = new ExcelUtil<SlRwork>(SlRwork.class);
        util.exportExcel(response, list, "报工单数据");
    }

    /**
     * 获取报工项详细信息
     */
    @PreAuthorize("@ss.hasPermi('sl:rwork:query')")
    @GetMapping(value = "/{rworkId}")
    public AjaxResult getInfo(@PathVariable("rworkId") Long rworkId)
    {
        AjaxResult ajax = AjaxResult.success();

        //获取模块列表
        ajax.put("modules", slModuleService.selectModuleAll());

        if (StringUtils.isNotNull(rworkId))
        {
            SlRwork slRwork = slRworkService.selectSlRworkByRworkId(rworkId);
            ajax.put(AjaxResult.DATA_TAG, slRwork);
            //获取模块对应的车间
            if(StringUtils.isNotNull(slRwork.getModuleId())){
                ajax.put("workshops", slWorkshopService.selectSlWorkshopListByModuleId(slRwork.getModuleId()));
            }
            //获取车间对应的大工序列表
            if(StringUtils.isNotNull(slRwork.getWorkshopId())){
                ajax.put("gprocesss", slGprocessService.selectSlGprocessListByWorkshopId(slRwork.getWorkshopId()));
            }
            //获取大工序对应的小工序列表
            if(StringUtils.isNotNull(slRwork.getGprocessId())){
                ajax.put("processs", slProcessService.selectSlProcessListByGprocessId(slRwork.getGprocessId()));
            }
        }
        return ajax;

    }

    /**
     * 打开新增报工项时获取页面中的选项内容
     */
    @GetMapping("/option")
    public AjaxResult rworkOptions(SlRwork slRwork)
    {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("modules", slModuleService.selectModuleAll());
        SlRwork lastSlRwork = slRworkService.selectSlRworkByLast(getLoginUser().getUsername(),DateUtils.dateTime(DateUtils.YYYY_MM_DD,DateUtils.getDate()));
        if(StringUtils.isNotNull(lastSlRwork)){
            lastSlRwork.setRworkId(null);
            ajax.put(AjaxResult.DATA_TAG, lastSlRwork);
            //获取模块对应的车间
            if(StringUtils.isNotNull(lastSlRwork.getModuleId())){
                ajax.put("workshops", slWorkshopService.selectSlWorkshopListByModuleId(lastSlRwork.getModuleId()));
            }
            //获取车间对应的大工序列表
            if(StringUtils.isNotNull(lastSlRwork.getWorkshopId())){
                ajax.put("gprocesss", slGprocessService.selectSlGprocessListByWorkshopId(lastSlRwork.getWorkshopId()));
            }
            //获取大工序对应的小工序列表
            if(StringUtils.isNotNull(lastSlRwork.getGprocessId())){
                ajax.put("processs", slProcessService.selectSlProcessListByGprocessId(lastSlRwork.getGprocessId()));
            }
        }else {
            if(slRwork.getModuleId()!=null){
                ajax.put("workshops",slWorkshopService.selectSlWorkshopListByModuleId(slRwork.getModuleId()));
            }
            if(slRwork.getWorkshopId()!=null){
                ajax.put("gprocesss",slGprocessService.selectSlGprocessListByWorkshopId(slRwork.getWorkshopId()));
            }
        }


        return ajax;
    }

    /**
     * 打开报工页面时获取报工人信息
     */
    @GetMapping(value =  "/user/{userName}" )
    public AjaxResult getRworkUser(@PathVariable("userName") String userName)
    {
        AjaxResult ajax = AjaxResult.success();

        SysDept sysDept =  sysDeptService.selectDeptById(getLoginUser().getDeptId());
        JSONObject userJson = new JSONObject();
        userJson.put("leaderUser",sysDept.getLeader());

        SlGprocess slGprocess = slGprocessService.selectSlGprocessByDeptId(sysDept.getDeptId());
        if(StringUtils.isNotNull(slGprocess)){
            userJson.put("gprocessId",slGprocess.getGprocessId());
            userJson.put("workshopId", slGprocess.getWorkshop().getWorkshopId());
            userJson.put("moduleId", slGprocess.getModule().getModuleId());
        }else {
            SlWorkshop slWorkshop = slWorkshopService.selectSlWorkshopByDeptId(sysDept.getDeptId());
            if(StringUtils.isNotNull(slWorkshop)){
                userJson.put("gprocessId",null);
                userJson.put("workshopId", slWorkshop.getWorkshopId());
                userJson.put("moduleId", slWorkshop.getModule().getModuleId());
            }else {
                SlModule slModule = slModuleService.selectSlModuleByDeptId(sysDept.getDeptId());
                if (StringUtils.isNotNull(slModule)){
                    userJson.put("gprocessId",null);
                    userJson.put("workshopId", null);
                    userJson.put("moduleId", slModule.getModuleId());
                }
            }
        }
        ajax.put(AjaxResult.DATA_TAG, userJson);
        return ajax;
    }

    //报工人常用操作人排序
    @GetMapping(value =  "/often/{userName}" )
    public AjaxResult getOftenUserList(@PathVariable("userName") String userName)
    {
        AjaxResult ajax = AjaxResult.success();
        List<String> userList = slRworkService.selectOftenUserList(userName);
        ajax.put(AjaxResult.DATA_TAG, userList);

        return ajax;
    }


    /**
     * 新增报工项
     */
    @PreAuthorize("@ss.hasPermi('sl:rwork:add')")
    @Log(title = "报工单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SlRwork slRwork)
    {

        slRwork.setCreateBy(getUsername());
        return toAjax(slRworkService.insertSlRwork(slRwork));
    }

    /**
     * 整张报工单提交
     */
    @PreAuthorize("@ss.hasPermi('sl:rwork:add')")
    @Log(title = "整张报工单提交", businessType = BusinessType.INSERT)
    @PostMapping("/daterws")
    public AjaxResult submitDateRworks(@RequestBody SlRworkDateForm slRworkDateForm)
    {
        return toAjax(slRworkService.insertDateRworks(slRworkDateForm));
    }

    /**
     * 修改报工单
     */
    @PreAuthorize("@ss.hasPermi('sl:rwork:edit')")
    @Log(title = "报工单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SlRwork slRwork)
    {
        slRwork.setUpdateBy(getUsername());
        return toAjax(slRworkService.updateSlRwork(slRwork));
    }


    /**
     * 更新报工单开始结束时间
     */
    @PreAuthorize("@ss.hasPermi('sl:rwork:edit')")
    @Log(title = "报工单", businessType = BusinessType.UPDATE)
    @PutMapping("/upd")
    public AjaxResult updateDateTime(@RequestBody SlRwork slRwork)
    {
        slRwork.setUpdateBy(getUsername());
        return toAjax(slRworkService.updateSlRworkDateTime(slRwork));
    }
    /**
     * 删除报工单
     */
    @PreAuthorize("@ss.hasPermi('sl:rwork:remove')")
    @Log(title = "报工单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{rworkIds}")
    public AjaxResult remove(@PathVariable Long[] rworkIds)
    {
        return toAjax(slRworkService.deleteSlRworkByRworkIds(rworkIds));
    }


}
